package config;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.loser.utils.trace.MDCUtil;
import com.loser.utils.trace.TraceUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class RestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (attributes == null) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        String traceId = request.getHeader(MDCUtil.TRACE_ID);
        if (StringUtils.isEmpty(traceId)) {
            traceId = MDCUtil.getTraceId();
            if (StringUtils.isEmpty(traceId)) {
                traceId = TraceUtil.getTraceId();
            }
        }
        requestTemplate.header(MDCUtil.TRACE_ID, traceId);
    }

}
